<template>
	<el-dialog class="Settlementbox" v-model="dialogVisible" title="订单结算" :width="corewiteh" :before-close="handleClose">
		<el-table :data="table" border :row-class-name="tableRowClassName">
			<el-table-column prop="title" show-overflow-tooltip :min-width="coreminwidth" label="名称">
				<template #default="scope">
					<div v-if="scope.row.summary" class="Horizontalspacing minaxgap">
						<div v-for="(item, index) in scope.row.value" :key="index" class="Channel Horizontalspacing minxgap"
							><div>{{ item.type }}:</div><el-tag size="small" type="danger">{{ item.plice }}</el-tag>
						</div>
					</div>
					<div v-else>{{ scope.row.title }} </div>
				</template>
			</el-table-column>
			<el-table-column label="数量" width="55">
				<template #default="scope">
					<div v-if="scope.row.summary" class="amountto"> {{ scope.row.quantity }}</div>
					<div v-else style="text-align: center">{{ scope.row.quantity }} </div>
				</template>
			</el-table-column>
			<el-table-column prop="Price" label="单价" show-overflow-tooltip min-width="70">
				<template #default="scope">
					<div v-if="scope.row.summary" class="amounttos"> ${{ scope.row.Price }} </div>
					<div v-else>${{ scope.row.Price }} </div>
				</template>
			</el-table-column>
		</el-table>
		<div class="Settlement">
			<el-form ref="form" :model="form" label-width="80px">
				<el-form-item label="渠道码:">
					<el-input v-model="form.code" size="small" @change="Channelcode" />
				</el-form-item>
				<el-form-item label="优惠券:">
					<el-select v-model="form.key" placeholder="优惠券" size="small" @change="input">
						<el-option v-for="(item, index) in couponskey" :key="index" :label="item.Conditions > 0 ? '满$' + item.Conditions + '减$' + item.Amount : '通用$' + item.Amount + '券'" :value="item.couponskey"></el-option>
					</el-select>
				</el-form-item>
			</el-form>
		</div>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="dialogVisible = false">取消</el-button>
				<el-button type="primary" @click="payment">支付</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script>
	import { mapState } from 'vuex'
	import { dataRequest as api } from '@/api/api'
	export default {
		props: ['info'],
		computed: {
			...mapState(['user']),
		},
		data() {
			return {
				corewiteh: '680px',
				coreminwidth: '359',
				form: {
					key: '',
					code: '',
				},
				couponskey: [],
				table: [],
				// tooltip: { effect: 'light' },
				dialogVisible: false,
			}
		},
		methods: {
			async payment() {
				// 传订单号 渠道码  优惠券码
				if (this.table[this.table.length - 1].Price < this.user.balance) {
					// 余额足够
					let data = { OrderNo: this.info.OrderNo, Channelcode: this.form.code, couponskey: this.form.key }
					let arr = await api(['Ordersettlement', data])
					if (arr.code == 200) {
						this.$message.success('购买成功')
						this.$emit('custom-event', '')
						this.dialogVisible = false
					} else {
						this.$message.error(`${arr.massage}:${arr.data}`)
					}
				} else {
					this.$message.error('余额不足')
				}
			},
			async Channelcode() {
				// 获取渠道码的信息
				if (this.form.code) {
					let arr = await api(['fetchChannelCode', { code: this.form.code }], 'v2', 'query')
					// 要判断的条件
					let judge = false
					if (arr.code == 200) {
						this.table[0].Channelcode = ''
						this.table[1] = this.summaryrow()
						const currentDate = new Date()
						const currentTimestamp = currentDate.getTime()
						if ((this.user.id == arr.data.userid || arr.data.userid == 0) && this.user.id != arr.data.BeneficiaryID && arr.data.state == 1 && (currentTimestamp >= arr.data.start_time || arr.data.start_time == 0) && (currentTimestamp <= arr.data.end_time || arr.data.end_time == 0)) {
							if (this.table[1].Price > arr.data.Conditions && (arr.data.Category == 0 || (arr.data.Category == this.table[0]['type'] && (arr.data.ProductID == this.table[0]['ProductID'] || arr.data.ProductID == 0)))) {
								// 满足条件
								this.table[0].Channelcode = arr.data.Amount
								// 再次计算优惠价
								this.table[1] = this.summaryrow()
								judge = true
							}
						}
					}

					if (!judge) {
						this.$message.error('渠道码不可用')
						// this.$message.success('购买成功')
					}
				}
			},
			// 优惠券
			input() {
				//这里计算优惠价格
				let couponskey = this.couponskey
				// console.log(this.table[0].coupons)
				for (let key in couponskey) {
					if (couponskey[key]['couponskey'] == this.form.key) {
						// 找到优惠券
						// 需要重新计算优惠价 去除原来的优惠价计算
						this.table[0].coupons = ''
						this.table[1] = this.summaryrow()
						if (this.table[1].Price > couponskey[key]['Conditions']) {
							// 满足条件
							this.table[0].coupons = couponskey[key]['Amount']
							// 再次计算优惠价
							this.table[1] = this.summaryrow()
						} else {
							this.$message.error('价格低于优惠券使用条件')
							this.form.key = ''
						}
						// 判断是否满足条件
					}
				}
			},
			// 计算价格
			async Calculateorders() {
				let arr = await api(['Calculateorders', [this.info]])
				console.log('订单结果', arr)
				if (arr.code == 200) {
					this.couponskey = arr.data[0].couponskey
					this.table = arr.data
					this.table[1] = this.summaryrow()
				}
				this.dialogVisible = true
				// 修改
			},
			// 汇总行计算
			summaryrow() {
				//总价(优惠后)
				// 活动优惠
				// 优惠卷优惠总价(暂时没有)
				let Price = 0
				let discount = 0
				let tabulation = []

				if (!this.table[0].summary) {
					if (this.table[0].discount) {
						// 存在优惠价
						Price += this.table[0].discount / 1
						discount += this.table[0].Price / 1 - this.table[0].discount / 1
						tabulation.push({ type: '活动抵扣', plice: '减 $' + discount })
					} else {
						Price += this.table[0].Price / 1
					}

					if (this.table[0].coupons) {
						// 存在优惠券
						Price = Price - this.table[0].coupons / 1
						tabulation.push({ type: '优惠券', plice: '减 $' + this.table[0].coupons })
					}
					// 判断有没有渠道优惠
					if (this.table[0].Channelcode) {
						// 存在优惠券
						Price = Price - this.table[0].Channelcode / 1
						tabulation.push({ type: '渠道优惠', plice: '减 $' + this.table[0].Channelcode })
					}
				}

				return {
					quantity: '合计',
					Price: Price > 0 ? Price : 0,
					value: tabulation,
					summary: true,
				}
			},
			// 设置行css
			tableRowClassName(arg) {
				const { row, rowIndex } = arg
				if (row.summary) {
					return 'warning-row'
				} else if (rowIndex === 3) {
					return ''
				}
			},
			handleClose(done) {
				this.$confirm('确认关闭？')
					.then(_ => {
						done()
					})
					.catch(_ => {})
			},

			handleResize() {
				// 使用媒体查询判断屏幕尺寸，并根据不同的尺寸修改播放器容器的大小
				console.log('监听')
				if (window.matchMedia('(max-width: 860px)').matches) {
					this.corewiteh = '3.5rem'
					this.coreminwidth = '180'
				} else {
					this.corewiteh = '680px'
					this.coreminwidth = '359'
				}
			},
		},
		mounted() {
			window.addEventListener('resize', this.handleResize)
			this.handleResize()
			this.Calculateorders()

			// 生命周期:
		},
		beforeDestroy() {
			window.removeEventListener('resize', this.handleResize)
		},
	}
</script>
<style scoped>
	.Settlement {
		display: grid;
		place-items: end;
	}
	.el-form-item {
		margin-bottom: 0px !important;
	}
	.Alreadydiscounted {
		font-size: 10px;
		color: #f56c6c;
	}
</style>
<style>
	.Settlementbox .el-dialog__body {
		padding-top: 10px !important;
		padding-bottom: 0px !important;
	}
	.Settlementbox .el-form-item__label {
		font-size: 14px;
		font-weight: bold;
	}
	.Settlementbox .el-table .warning-row {
		--el-table-tr-bg-color: var(--el-table-border-color);
	}

	.Settlementbox .el-table--enable-row-hover .el-table__body tr:hover > td.el-table__cell {
		background-color: transparent !important;
	}
	.Settlementbox .Channel {
		font-size: 12px;
	}
	.Settlementbox .amountto {
		font-weight: bold;
		color: black;
	}
	.Settlementbox .amounttos {
		font-weight: bold;
		font-size: 18px;
		color: #f56c6c;
	}
</style>
<!-- 订单生成 -->
<!-- 获取订单  也是根据不同商品类型分类获取 -->
<!-- 后端处理订单 通过订单号辨别类型 先要计算余额够不够  不够要返回 然后再交易  比如课程  后端处理课程订单的时候 查询订单包含的课程  赠送包含的课程  订单价格0即可 -->
<!-- 优惠卷表 dex_coupons  要重做   领取记录表还没做 -->
<!-- 一张表记录 优惠卷金额  使用开始时间  结束时间    领取开始时间  结束时间   领取条件 自动发放的话 手动领取的需要在领卷中心手动领取  用户登陆时 就给生成 -->
<!-- 一张表记录用户的领取记录 用户ID  优惠卷ID   优惠卷KEY  优惠卷状态 使用时间  使用的订单号  -->
<!-- {商品ID  商品类型} -->
